package com.example.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import com.example.database.DbManager;
import com.example.juyixia.Activity_chatActivity;
import com.exanple.data.Activeinfo;
import com.exanple.data.ChatMsgEntity;

import android.app.Service;
import android.content.Intent;
import android.content.res.Resources.NotFoundException;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.Toast;

public class RecmessService extends Service {
	private boolean isRun;// 线程是否继续的标志
	private Handler handler1; // 显示当前时间线程消息处理器。
	public static final String bm = "utf-8";
	private DbManager mgr; 
	private ChatMsgEntity recmess;
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate(); 
	}
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		mgr = new DbManager(this);
		isRun=true;
		 
		 new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						Intent intent=new Intent();
						intent.setAction(Activity_chatActivity.ACTION_UPDATEUI);
						ServerSocket serverSocket = new ServerSocket(36363);
						while (isRun) {
							Socket client = serverSocket.accept();
							BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream(), bm));
							String str = in.readLine();
							JSONObject recmessjson =new JSONObject(str);
							JSONTokener messParser = new JSONTokener(recmessjson.toString()); 
							 JSONObject messagejson = (JSONObject) messParser.nextValue();
							 recmess=new ChatMsgEntity(messagejson.getString("发送人"),messagejson.getString("接收人"),messagejson.getString("发送时间"),messagejson.getString("消息内容"));
							mgr.add(recmess);
							 sendBroadcast(intent);  
							Message msg = new Message();
							handler1.sendMessage(msg);
						}
					}catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} 

				}
			}).start();// 默认线程不启动，必须自己start()
		 handler1 = new Handler(new Handler.Callback() {// 这样写，就不弹出什么泄漏的警告了
				@Override
				public boolean handleMessage(Message msg) {
					try {
						Toast.makeText(getApplicationContext(), "您收到"+recmess.getSendname()+"发来的新消息！",
							     Toast.LENGTH_SHORT).show();
					} catch (NotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} 
					return false;
				}
			});
		  return START_STICKY;
	}

}
